package com.wannengbang.cloudleader.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Region;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatImageView;

import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.utils.Dp2Px;


/**
 * Time: 2019/7/18
 * Description:
 */

public class RoundImageView extends AppCompatImageView {
    float width, height;
    private float radius;

    public RoundImageView(Context context) {
        this(context, null);
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        getAttrs(context, attrs);
    }

    private void getAttrs(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView);
        radius = typedArray.getDimension(R.styleable.RoundImageView_image_round, getResources().getDimension(R.dimen.dp_5));

        typedArray.recycle();
    }

    public float getRadius() {
        return radius;
    }

    /**
     * @param radius 单位是dp
     */
    public void setRadius(int radius) {
        this.radius = Dp2Px.dp2Px(radius);
        invalidate();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        width = getWidth();
        height = getHeight();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = MeasureSpec.getSize(widthMeasureSpec);
        height = MeasureSpec.getSize(heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        if (width > radius && height > radius) {

            Path path = new Path();
            path.moveTo(radius, 0);
            path.lineTo(width - radius, 0);
            path.quadTo(width, 0, width, radius);
            path.lineTo(width, height - radius);
            path.quadTo(width, height, width - radius, height);
            path.lineTo(radius, height);
            path.quadTo(0, height, 0, height - radius);
            path.lineTo(0, radius);
            path.quadTo(0, 0, radius, 0);
            canvas.clipPath(path, Region.Op.INTERSECT);
        }

        super.onDraw(canvas);
    }
}
